#!/bin/bash

# 0. 导入依赖
if [ ! -e define.sh ]; then
    # 当前目录没有依赖文件,下载依赖
    wget https://gitee.com/askeynil/AskConfiguration/raw/master/define.sh
    source define.sh
    rm -rf define.sh
else
    source define.sh
fi

# 1. 判断是否安装了
if [ -e ~/anaconda3 ]; then
    success "已经安装了 anaconda "
    exit
fi

install curl

# 2. 查找 anaconda 的最新下载连接
url=`curl https://www.anaconda.com/distribution/ | grep -oP "Anaconda3-.*?-Linux-x86_64\.sh"`

url=`/usr/bin/env python -c "import sys; print(sys.argv[1].split('\n')[0])" $url`

url="https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/$url"


# 3. 下载 anaconda 源文件
filename=/tmp/anaconda.sh
wget -O $filename $url

# 4. 下载完成，执行 anaconda.sh
bash $filename -b

# 5. 设置anaconda
write() {
    write_bashrc(){
        echo "$1" >> $rcname
    }
    rcname=$1
    write_bashrc '# >>> conda initialize >>>'
    write_bashrc '# !! Contents within this block are managed by 'conda init' !!'
    write_bashrc '__conda_setup="$('/home/askeynil/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"'
    write_bashrc 'if [ $? -eq 0 ]; then'
    write_bashrc '    eval "$__conda_setup"'
    write_bashrc 'else'
    write_bashrc '    if [ -f "/home/askeynil/anaconda3/etc/profile.d/conda.sh" ]; then'
    write_bashrc '        . "/home/askeynil/anaconda3/etc/profile.d/conda.sh"'
    write_bashrc '    else'
    write_bashrc '        export PATH="/home/askeynil/anaconda3/bin:$PATH"'
    write_bashrc '    fi'
    write_bashrc 'fi'
    write_bashrc 'unset __conda_setup'
    write_bashrc '# <<< conda initialize <<<'
}

# 5.1 添加到 bashrc
if [ ! -n "`cat ~/.bashrc | grep "conda initialize"`" ]; then
    write ~/.bashrc
fi
success "conda 环境变量已经添加到 bashrc 中"

# 5.2 添加到 zshrc
if [ -e ~/.zshrc ]; then
    if [ ! -n "`cat ~/.zshrc | grep "conda initialize"`" ]; then
        write ~/.zshrc
    fi
else
    loading "未安装 zsh, 不添加 zshrc"
fi
success "conda 环境变量已经添加到 zshrc 中"

# 6. 默认不自动激活 base 环境
# 6.1 激活环境变量
. ~/.bashrc
# 6.2 关闭自动激活
conda config --set auto_activate_base false

success "conda 安装完成...."

# 7. 删除下载的文件
rm -rf $filename